﻿
using GCC.Container.Abstracts;

using GCCGrpc.APMServer;

using Grpc.Core;

namespace System.APMServer
{
    [GCCGRPCServer]
    public class Service : GCCGrpc.APMServer.APM.APMBase
    {
        private readonly AbsGCCLogger<Service> _logger;
        public Service(AbsGCCLogger<Service> logger)
        {
            _logger = logger;
        }
        public override Task<SetTraceInfoResponse> SetTraceInfo(SetTraceInfoRequest request, ServerCallContext context)
        {
            return Task.Run(() =>
            {
                var res = TraceManager.Instance.PushItem(new DBModel.TraceItem()
                {
                    Created = request.CreatedTime,
                    PointName = request.PointName,
                    ResourceName = request.ResourceName,
                    SessionID = request.SessionID,
                    Type = request.Type,
                    Value = request.Value,
                    From = request.From,
                    Path = request.Path,
                    Method = request.Method,
                });

                if (!res)
                {
                    _logger.Information("Save traceitem failed.May be apm server init failed.");
                }

                return new SetTraceInfoResponse();
            });
        }

        public override Task<GetTraceInfoByTimeResponse> GetTraceInfoByTime(GetTraceInfoByTimeRequest request, ServerCallContext context)
        {

            return Task.Run(() =>
            {
                var res = new GetTraceInfoByTimeResponse();
                var dbRes = TraceManager.Instance.GetByMinTime(request.MinTime);
                dbRes.ForEach(item =>
                {
                    res.Items.Add(new GetTraceInfoItem()
                    {
                        Created = item.Created,
                        PointName = item.PointName,
                        ResourceName = item.ResourceName,
                        SessionID = item.SessionID,
                        Type = item.Type,
                        Value = item.Value,
                        From = item.From,
                        Method = item.Method,
                        Path = item.Path,
                    });
                });
                return res;
            });
        }
    }
}
